package com.scalar.chiptrack.adaptor.ikanos.silterra;

import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.ScalarException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: ChandraSekhar
 * Date: Sep 14, 2006
 * Time: 3:56:12 AM
 */
public class SilterraDAO implements AdaptorConstants
{
     private static Logger s_logger = null;

    /**
    * @param dbTransaction
    * @param wipList
    * @throws com.scalar.ScalarException
    */
    public static void saveSilterraWipInfo( DBTransaction dbTransaction, ArrayList wipList ) throws ScalarException
    {
     Connection conn         = null;
     PreparedStatement pstmt = null;
     boolean success         = false;

     SilterraWipInfo silterraWipInfo = null;

     try
     {
         // Get the connection from regular datasource if its not in a manual transaction
         if( dbTransaction == null )
         {
             conn = DataSource.getConnection();
         }
         else
         {
             conn = dbTransaction.getConnection();
         }

         Calendar cal = Calendar.getInstance();
         java.util.Date todayDate = cal.getTime();
         String currentDate = StringUtils.formatDateToString( todayDate, "MM/dd/yyyy" );
         // Step 1
         // Delete all THE PREVIOUS DATA IN TABLE
         /*pstmt = conn.prepareStatement("DELETE FROM Silttera_Wip_Status_Table");
         pstmt.executeUpdate();
         pstmt.close();
         pstmt = null;*/

         // Delete all THE PREVIOUS DATA IN HISTORY TABLE
         pstmt = conn.prepareStatement("DELETE FROM Silttera_Wip_Status_History_Table WHERE ADAPTOR_DATE = ?");
         pstmt.setString(1,currentDate);
         pstmt.executeUpdate();
         pstmt.close();
         pstmt = null;

         pstmt = conn.prepareStatement( "{ call sp_save_silterra_wip_info ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) }" );

         Iterator lotEventHistoryIterator = wipList.iterator();
         while( lotEventHistoryIterator.hasNext() )
         {
             silterraWipInfo = ( SilterraWipInfo ) lotEventHistoryIterator.next();

             //log( wipList + "\n" );

             pstmt.setString( 1,  silterraWipInfo.getTechnology() );
             pstmt.setString( 2,  silterraWipInfo.getDevice() );
             pstmt.setString( 3,  silterraWipInfo.getLotId() );
             pstmt.setString( 4,  silterraWipInfo.getLotType() );
             pstmt.setString( 5,  silterraWipInfo.getPriority() );
             pstmt.setString( 6,  silterraWipInfo.getStartQty() );
             pstmt.setString( 7,  silterraWipInfo.getCurrentQty() );
             pstmt.setString( 8,  silterraWipInfo.getPlan() );
             pstmt.setString( 9,  silterraWipInfo.getStep() );
             pstmt.setString( 10, silterraWipInfo.getStepSeq() );
             pstmt.setString( 11, silterraWipInfo.getMaskSeq() );
             pstmt.setString( 12, silterraWipInfo.getLotStartDate() );
             pstmt.setString( 13, silterraWipInfo.getOriginalShipDate() );
             pstmt.setString( 14, silterraWipInfo.getProjectedShipDate() );
             pstmt.setString( 15, silterraWipInfo.getSoNumber() );
             pstmt.setString( 16, silterraWipInfo.getPoNUmber() );
             pstmt.setString( 17, silterraWipInfo.getRemarks() );
             pstmt.setString( 18, currentDate);

             pstmt.addBatch();
         }

         pstmt.executeBatch();
         success = true;
     }

     catch( SQLException sqle )
     {
         sqle.printStackTrace();
         throw new ScalarException( "Could not save Silterrea Wip Information into database", sqle );
     }

     finally
     {

         // Commit/Rollback here it selef -- if its not in a manual transaction
         if( dbTransaction == null )
         {
             try
             {
                 if( conn != null )
                 {
                     if( success == true )
                     {
                         conn.commit();
                     }
                     else
                     {
                         conn.rollback();
                     }
                 }
             }
             catch( SQLException ignore )
             {
             }
         }

         if( pstmt != null )
         {
             try
             {
                 pstmt.close();
             }
             catch( SQLException ignore )
             {
             }
         }
         if( conn != null )
         {
             try
             {
                 conn.close();
             }
             catch( SQLException ignore )
             {
             }
         }
     }
    }

    public static void saveSilterraShipInfo(DBTransaction dbTransaction, ArrayList shipList) throws ScalarException {
       Connection conn = null;
       PreparedStatement pstmt = null;
       boolean success = false;
       String lotNumber = null;

       SilterraShipInfo silterraShipInfo = null;

       try {
           // Get the connection from regular datasource if its not in a manual transaction
           if (dbTransaction == null) {
               conn = DataSource.getConnection();
           } else {
               conn = dbTransaction.getConnection();
           }

           Calendar cal = Calendar.getInstance();
           java.util.Date todayDate = cal.getTime();
           String currentDate = StringUtils.formatDateToString(todayDate, "MM/dd/yyyy");
           // Step 1
           // Delete all THE PREVIOUS DATA IN TABLE
           /*pstmt = conn.prepareStatement("DELETE FROM Silterra_Ship_Status_Table");
           pstmt.executeUpdate();
           pstmt.close();
           pstmt = null;*/

           // Delete all THE PREVIOUS DATA IN HISTORY TABLE
           pstmt = conn.prepareStatement("DELETE FROM Silterra_Ship_Status_History_Table WHERE ADAPTOR_DATE = ?");
           pstmt.setString(1, currentDate);
           pstmt.executeUpdate();
           pstmt.close();
           pstmt = null;

           pstmt = conn.prepareStatement("{ call sp_save_silterra_ship_info ( ?, ?, ?, ?, ?, ?, ?, ?, ? ) }");

           Iterator shipIterator = shipList.iterator();
           while ( shipIterator.hasNext()) {
               silterraShipInfo = ( SilterraShipInfo ) shipIterator.next();

               lotNumber = silterraShipInfo.getFwLotID();
               if (lotNumber == null) continue;
               //log( shipList + "\n" );

               pstmt.setString(1, silterraShipInfo.getCustomerDeviceID());
               pstmt.setString(2, silterraShipInfo.getFwDeviceID() );
               pstmt.setString(3, silterraShipInfo.getFwLotID() );
               pstmt.setString(4, silterraShipInfo.getPoNumber() );
               pstmt.setString(5, silterraShipInfo.getInvoiceNumber());
               pstmt.setString(6, silterraShipInfo.getQuantity());
               pstmt.setString(7, silterraShipInfo.getShipmentDate() );
               pstmt.setString(8, silterraShipInfo.getShipmentNumber() );
               pstmt.setString(9, currentDate);

               pstmt.addBatch();
           }

           pstmt.executeBatch();
           success = true;
       }

       catch (SQLException sqle) {
           sqle.printStackTrace();
           throw new ScalarException("Could not save Silterra Ship Information into database", sqle);
       }

       finally {

           // Commit/Rollback here it selef -- if its not in a manual transaction
           if (dbTransaction == null) {
               try {
                   if (conn != null) {
                       if (success == true) {
                           conn.commit();
                       } else {
                           conn.rollback();
                       }
                   }
               }
               catch (SQLException ignore) {
               }
           }

           if (pstmt != null) {
               try {
                   pstmt.close();
               }
               catch (SQLException ignore) {
               }
           }
           if (conn != null) {
               try {
                   conn.close();
               }
               catch (SQLException ignore) {
               }
           }
       }
    }

    /**
    *
    * @param message
    */
    private static void log (String message)
    {
        if ( message == null) return;

        if (s_logger != null)
        {
            synchronized (s_logger)
            {
                s_logger.logDebug (message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println (message);
        }
    }

    public static void setLogger (Logger logger)
    {
        s_logger = logger;
    }

}
